<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
        }
        input[type="text"], input[type="number"], select {
            width: 200px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .btn-success {
            background-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .search-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .pagination {
            margin-top: 20px;
            text-align: center;
        }
        .pagination button {
            margin: 0 5px;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>产品管理</h1>
        
        <div id="form-container">
            <h3 id="form-title">新增产品</h3>
            <form id="product-form">
                <input type="hidden" id="product-id">
                <div class="form-group">
                    <label for="name">名称:</label>
                    <input type="text" id="name" required>
                </div>
                <div class="form-group">
                    <label for="price">价格:</label>
                    <input type="number" id="price" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="brandId">品牌:</label>
                    <select id="brandId" required>
                        <option value="">请选择品牌</option>
                    </select>
                </div>
                <button type="submit" id="submit-btn">保存</button>
                <button type="button" onclick="resetForm()">重置</button>
            </form>
        </div>
        
        <div class="search-section">
            <h3>搜索条件</h3>
            <div class="form-group">
                <label for="search-name">产品名称:</label>
                <input type="text" id="search-name" placeholder="支持模糊查询">
            </div>
            <div class="form-group">
                <label for="search-min-price">最低价格:</label>
                <input type="number" id="search-min-price" step="0.01" placeholder="最低价格">
            </div>
            <div class="form-group">
                <label for="search-max-price">最高价格:</label>
                <input type="number" id="search-max-price" step="0.01" placeholder="最高价格">
            </div>
            <div class="form-group">
                <label for="search-brand">品牌:</label>
                <select id="search-brand">
                    <option value="">全部品牌</option>
                </select>
            </div>
            <button onclick="searchProducts()">搜索</button>
            <button onclick="loadProducts()">重置搜索</button>
        </div>
        
        <div style="margin-top: 30px;">
            <button onclick="loadProducts()">刷新列表</button>
        </div>
        
        <table id="product-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>名称</th>
                    <th>价格</th>
                    <th>品牌</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="product-tbody">
            </tbody>
        </table>
        
        <div class="pagination">
            <button onclick="changePage(-1)">上一页</button>
            <span id="page-info">第 1 页</span>
            <button onclick="changePage(1)">下一页</button>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let totalPages = 1;
        let brands = [];
        
        // 页面加载时获取数据
        window.onload = function() {
            loadBrands();
            loadProducts();
        };
        
        // 加载品牌列表
        function loadBrands() {
            fetch('http://127.0.0.1:8080/api/brands')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        brands = data.data;
                        updateBrandSelects();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
        
        // 更新品牌选择框
        function updateBrandSelects() {
            const brandSelect = document.getElementById('brandId');
            const searchBrandSelect = document.getElementById('search-brand');
            
            // 清空现有选项
            brandSelect.innerHTML = '<option value="">请选择品牌</option>';
            searchBrandSelect.innerHTML = '<option value="">全部品牌</option>';
            
            // 添加品牌选项
            brands.forEach(brand => {
                brandSelect.innerHTML += `<option value="${brand.id}">${brand.name}</option>`;
                searchBrandSelect.innerHTML += `<option value="${brand.id}">${brand.name}</option>`;
            });
        }
        
        // 加载产品列表
        function loadProducts() {
            fetch(`http://127.0.0.1:8080/api/products/page?page=${currentPage}&size=10`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayProducts(data.data);
                        totalPages = Math.ceil(data.total / 10);
                        updatePageInfo();
                    } else {
                        alert('加载失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载失败');
                });
        }
        
        // 搜索产品
        function searchProducts() {
            const name = document.getElementById('search-name').value;
            const minPrice = document.getElementById('search-min-price').value;
            const maxPrice = document.getElementById('search-max-price').value;
            const brandId = document.getElementById('search-brand').value;
            
            let url = `http://127.0.0.1:8080/api/products/search?page=${currentPage}&size=10`;
            if (name) url += `&name=${encodeURIComponent(name)}`;
            if (minPrice) url += `&minPrice=${minPrice}`;
            if (maxPrice) url += `&maxPrice=${maxPrice}`;
            if (brandId) url += `&brandId=${brandId}`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayProducts(data.data);
                        totalPages = Math.ceil(data.total / 10);
                        updatePageInfo();
                    } else {
                        alert('搜索失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('搜索失败');
                });
        }
        
        // 显示产品列表
        function displayProducts(products) {
            const tbody = document.getElementById('product-tbody');
            tbody.innerHTML = '';
            
            products.forEach(product => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.id}</td>
                    <td>${product.name}</td>
                    <td>￥${product.price}</td>
                    <td>${product.brand ? product.brand.name : ''}</td>
                    <td>
                        <button onclick="editProduct(${product.id})">编辑</button>
                        <button class="btn-danger" onclick="deleteProduct(${product.id})">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }
        
        // 编辑产品
        function editProduct(id) {
            fetch(`http://127.0.0.1:8080/api/products/${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const product = data.data;
                        document.getElementById('product-id').value = product.id;
                        document.getElementById('name').value = product.name;
                        document.getElementById('price').value = product.price;
                        document.getElementById('brandId').value = product.brandId || '';
                        document.getElementById('form-title').textContent = '编辑产品';
                        document.getElementById('submit-btn').textContent = '更新';
                    } else {
                        alert('获取产品信息失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取产品信息失败');
                });
        }
        
        // 删除产品
        function deleteProduct(id) {
            if (confirm('确定要删除这个产品吗？')) {
                fetch(`http://127.0.0.1:8080/api/products/${id}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('删除成功');
                        loadProducts();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
        }
        
        // 表单提交
        document.getElementById('product-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const id = document.getElementById('product-id').value;
            const name = document.getElementById('name').value;
            const price = document.getElementById('price').value;
            const brandId = document.getElementById('brandId').value;
            
            const product = {
                name: name,
                price: parseFloat(price),
                brandId: brandId ? parseInt(brandId) : null
            };
            
            const url = id ? `http://127.0.0.1:8080/api/products/${id}` : 'http://127.0.0.1:8080/api/products';
            const method = id ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(product)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(id ? '更新成功' : '新增成功');
                    resetForm();
                    loadProducts();
                } else {
                    alert((id ? '更新' : '新增') + '失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert((id ? '更新' : '新增') + '失败');
            });
        });
        
        // 重置表单
        function resetForm() {
            document.getElementById('product-form').reset();
            document.getElementById('product-id').value = '';
            document.getElementById('form-title').textContent = '新增产品';
            document.getElementById('submit-btn').textContent = '保存';
        }
        
        // 切换页面
        function changePage(delta) {
            const newPage = currentPage + delta;
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                loadProducts();
            }
        }
        
        // 更新页面信息
        function updatePageInfo() {
            document.getElementById('page-info').textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
        }
    </script>
</body>
</html> 